﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace Genuilder.Extensibility
{
	public class FileCodeItemMementoRepository : CodeItemMementoRepository
	{
		private readonly FileInfo _MementoFile;
		public FileInfo MementoFile
		{
			get
			{
				return _MementoFile;
			}
		}
		public FileCodeItemMementoRepository(FileInfo mementoFile)
		{
			if(mementoFile == null)
				throw new ArgumentNullException("mementoFile");
			_MementoFile = mementoFile;
		}
		#region CodeItemMementoRepository Members

		public IEnumerable<DirectoryCodeRepository.CodeItemMemento> LoadCodeItemMementos()
		{
			if(!MementoFile.Exists)
				return new List<Genuilder.Extensibility.DirectoryCodeRepository.CodeItemMemento>();
			using(var fs = File.Open(MementoFile.FullName, FileMode.Open))
			{
				XmlSerializer serializer = new XmlSerializer(typeof(List<Genuilder.Extensibility.DirectoryCodeRepository.CodeItemMemento>));
				return (List<Genuilder.Extensibility.DirectoryCodeRepository.CodeItemMemento>)serializer.Deserialize(fs);
			}
		}

		public void SaveCodeItemMementos(IEnumerable<DirectoryCodeRepository.CodeItemMemento> mementos)
		{
			mementos = mementos.ToList();
			using(var fs = MementoFile.Open(FileMode.Create))
			{
				XmlSerializer serializer = new XmlSerializer(typeof(List<Genuilder.Extensibility.DirectoryCodeRepository.CodeItemMemento>));
				serializer.Serialize(fs, mementos);
			}
		}

		#endregion
	}
}
